package com.gxuwz.medical.web.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;









import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;

import com.gxuwz.medical.dao.FamilyDao;
import com.gxuwz.medical.dao.FamilyMemberDao;
import com.gxuwz.medical.dao.MoneyDao;
import com.gxuwz.medical.domain.family.Family;
import com.gxuwz.medical.domain.family.FamilyMember;
import com.gxuwz.medical.domain.money.Money;
import com.gxuwz.medical.domain.money.Payperiod;
import com.gxuwz.medical.exception.DbException;
import com.gxuwz.medical.tools.DateUtil;

public class MoneyServlet extends BaseServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String m = request.getParameter("m");
		if ("find".equals(m)) {
			find(request, response);
		} else if ("get".equals(m)) {
			findAllMember(request, response);
		} else if ("export".equals(m)) {
			try {
				exportAccountData(request, response);
			} catch (DbException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if ("add".equals(m)) {
			addMoney(request, response);
			process(request, response, "/page/money/alread_join_list.jsp");
		} else if ("come".equals(m)) {
			process(request, response, "/page/money/money_edit.jsp");
		} else if ("edit".equals(m)) {
			edit(request, response);
			process(request, response, "/page/money/alread_join_list.jsp");
		} else {
			error(request, response);
		}
	}

	private void find(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String name = request.getParameter("familyholdername");
			System.out.println("页面传过来的查询字段是啥" + name);
			if (name == null) {
				request.setAttribute("model", null);
				process(request, response, "/page/money/money_find.jsp");
			} else {
				FamilyMemberDao familyMemberDao = new FamilyMemberDao();
				List<FamilyMember> list = familyMemberDao.findByName(name);
				System.out.println("看查出个什么" + list);
				request.setAttribute("model", list);
				process(request, response, "/page/money/money_find.jsp");
			}

		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	/**
	 * 这里需要查询出未缴费的家庭成员
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void findAllMember(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			String familycode = request.getParameter("id");
			System.out.println("页面传过来的家庭编号是啥" + familycode);
			FamilyMemberDao familyMemberDao = new FamilyMemberDao();
			List<FamilyMember> list = familyMemberDao.findAll(familycode);
			System.out.println("查出的所有家庭成员========" + list);
			//缴费年份，默认为当前系统时间对应的年份
			int payYear=DateUtil.getYear(new java.util.Date());
			//根据年份读取并显示缴费标准
	        Payperiod payperiod=new Payperiod(payYear);
	        request.setAttribute("amount", payperiod.getAmount());
			request.setAttribute("model", list);
			process(request, response, "/page/money/money_list.jsp");

		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	/**
	 * 1.解析页面传过来的json数据
	 * 2.将json数据一一存入数据库
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void addMoney(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			
			String dat = request.getParameter("chioce");
			JSONArray jArray=JSONArray.fromObject(dat);
			System.out.println("============看看解析了没" +jArray);
			if(jArray.size()>0){
				for(int i = 0;i < jArray.size();i++){
					JSONObject json = (JSONObject) jArray.get(i);
					String name = json.getString("name");
					String cs = json.getString("cmscode");
					MoneyDao moneyDao = new MoneyDao();
					List<Money> in = moneyDao.find(name, cs);
					System.out.println("看他是否存在" + in);
					if (in.isEmpty()) {
						System.out.println("进入null方法---add");
						String operator = request.getParameter("operator");
						String invoicenumber = request.getParameter("invoicenumber");
						//发票号的处理
						DateFormat format = new SimpleDateFormat("yyMMddhhmmss");
						Date date = new Date();
						String invo=format.format(date);
						request.getSession().setAttribute("invoicenumber", invo);
						String aggregate=request.getParameter("amount");

						Money money = new Money();
						money.setName(name);
						money.setStandard("参照今年标准");
						money.setLasttime("2019-5-16");
						money.setEffectiveage("3");
						money.setPay("未缴费");
						money.setAggregate(aggregate);
						money.setInvoicenumber(invo);
						money.setOperator(operator);
						money.setCmscode(cs);

						money.add();
				  }
			   }
			} else {
				System.out.println("参合-----已存在");
			}
		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	private void edit(HttpServletRequest request, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			String id = request.getParameter("id");
			String name = request.getParameter("name");
			String standard = request.getParameter("standard");
			String lasttime = request.getParameter("lasttime");
			String effectiveage = request.getParameter("effectiveage");
			String pay = request.getParameter("pay");
			String aggregate = request.getParameter("aggregate");
			String invoicenumber = request.getParameter("invoicenumber");
			String operator = request.getParameter("operator");
			Money money = new Money();
			money.setId(id);
			money.setName(name);
			money.setStandard(standard);
			money.setLasttime(lasttime);
			money.setEffectiveage(effectiveage);
			money.setPay(pay);
			money.setAggregate(aggregate);
			money.setInvoicenumber(invoicenumber);
			money.setOperator(operator);
			money.edit(id, name, standard, lasttime, effectiveage, pay,
					aggregate, invoicenumber, operator);
		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	/**
	 * excel导出
	 * 
	 * @param req
	 * @param resp
	 *            void
	 * @throws IOException
	 * @throws DbException
	 */
	@SuppressWarnings("unused")
	private void exportAccountData(HttpServletRequest request,
			HttpServletResponse response) throws IOException, DbException {
		try {
			String invo=(String) request.getSession().getAttribute("invoicenumber");//获取session中的
			MoneyDao moneyDao = new MoneyDao();
			List<Money> list = moneyDao.findList(invo);//根据发票号，查出同一批的参合登记人，并打印出

			if (null != list && list.size() > 0) {

				String fileName = "参合人员缴费信息.xls";
				response.setHeader(
						"Content-disposition",
						"attachment;filename="
								+ new String(fileName.getBytes("gb2312"),
										"ISO8859-1")); // 设置文件头编码格式
				response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");// 设置类型
				response.setHeader("Cache-Control", "no-cache");// 设置头
				response.setDateHeader("Expires", 0);// 设置日期头

				HSSFWorkbook book = new HSSFWorkbook();

				HSSFSheet sheet = book.createSheet();
				CellStyle cellStyle = book.createCellStyle();

				cellStyle.setDataFormat(book.createDataFormat().getFormat(
						"yyyy-MM-dd"));

				CellRangeAddress region = new CellRangeAddress(0, // first row
						0, // last row
						0, // first column
						8 // last column
				);

				sheet.addMergedRegion(region);

				HSSFRow Row = sheet.createRow(0);
				HSSFCell headCell = Row.createCell(0);
				headCell.setCellValue("参合人员缴费登记信息");

				// 设置单元格格式居中
				cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
				headCell.setCellStyle(cellStyle);

				// 添加表头行
				Row = sheet.createRow(1);
				// 添加表头内容
				headCell = Row.createCell(0);
				headCell.setCellValue("姓名");
				headCell.setCellStyle(cellStyle);

				headCell = Row.createCell(1);
				headCell.setCellValue("是否设置标准");
				headCell.setCellStyle(cellStyle);

				headCell = Row.createCell(2);
				headCell.setCellValue(" 最后缴费时间");
				headCell.setCellStyle(cellStyle);

				headCell = Row.createCell(3);
				headCell.setCellValue("有效年限");
				headCell.setCellStyle(cellStyle);

				headCell = Row.createCell(4);
				headCell.setCellValue("是否已缴费");
				headCell.setCellStyle(cellStyle);

				headCell = Row.createCell(5);
				headCell.setCellValue("缴费金额");
				headCell.setCellStyle(cellStyle);

				headCell = Row.createCell(6);
				headCell.setCellValue("发票号");
				headCell.setCellStyle(cellStyle);

				headCell = Row.createCell(7);
				headCell.setCellValue("登记员");
				headCell.setCellStyle(cellStyle);

				
				for (int i = 0; i < list.size(); i++) {
					Money account = list.get(i);
					Row row = sheet.createRow((int) i + 2);

					Cell cell1 = row.createCell(0);
					cell1.setCellValue(account.getName());

					Cell cell2 = row.createCell(1);
					cell2.setCellValue(account.getStandard());
					Cell cell3 = row.createCell(2);
					cell3.setCellValue(account.getLasttime());
					Cell cell4 = row.createCell(3);
					cell4.setCellValue(account.getEffectiveage());
					Cell cell5 = row.createCell(4);
					cell5.setCellValue(account.getPay());

					Cell cell6 = row.createCell(5);
					cell6.setCellValue(account.getAggregate());
					cell6.setCellStyle(cellStyle);

					Cell cell7 = row.createCell(6);
					cell7.setCellStyle(cellStyle);
					cell7.setCellValue(account.getInvoicenumber());

					Cell cell8 = row.createCell(7);
					cell8.setCellStyle(cellStyle);
					cell8.setCellValue(account.getOperator());
				
				}

				book.write(response.getOutputStream());

				response.getOutputStream().flush();
				response.getOutputStream().close();
			}
		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	/*
	 * private void find(HttpServletRequest request, HttpServletResponse
	 * response) throws ServletException, IOException { try { String
	 * familyholdername = request.getParameter("familyholdername");
	 * System.out.println("页面传过来的查询字段是啥"+familyholdername); if(familyholdername
	 * == null){ request.setAttribute("model", null); process(request, response,
	 * "/page/money/money_find.jsp"); }else { MoneyDao moneyDao = new
	 * MoneyDao(); List<Money> list =
	 * moneyDao.findListByFamilyholdername(familyholdername);
	 * System.out.println("看查出个什么"+list); request.setAttribute("model", list);
	 * process(request, response, "/page/money/money_find.jsp"); }
	 * 
	 * 
	 * } catch (Exception e) { e.printStackTrace();
	 * 
	 * } }
	 * 
	 * private void AllList (HttpServletRequest request, HttpServletResponse
	 * response) throws ServletException, IOException { try { String
	 * standard=request.getParameter("standard"); String
	 * cmscode=request.getParameter("cmscode"); String
	 * name=request.getParameter("name"); String
	 * relative=request.getParameter("relative"); String
	 * idcard=request.getParameter("idcard"); String
	 * sex=request.getParameter("sex"); String pay=request.getParameter("pay");
	 * 
	 * String lasttime=request.getParameter("lasttime"); String
	 * effectiveage=request.getParameter("effectiveage"); String
	 * aggregate=request.getParameter("aggregate"); String
	 * invoicenumber=request.getParameter("invoicenumber"); String
	 * operator=request.getParameter("paoperatory");
	 * 
	 * String familycode=request.getParameter("id");//获取当前户主的家庭编号
	 * System.out.println("页面传过来的家庭编号"+familycode); MoneyDao moneyDao = new
	 * MoneyDao(); List<Money> list = moneyDao.findAll(familycode);
	 * System.out.println("看查出个什么"+list); request.setAttribute("model", list);
	 * 
	 * //查询出来之后，把参合人员信息保存到缴费表里，第一次查询肯定就没缴费，所以表里面信息只有已知信息 for(int
	 * i=0;i<list.size();i++){ //查询缴费表有没有这个成员 List<Money> member =
	 * moneyDao.findList(list.get(i).getName());
	 * System.out.println("看看这个成员姓名"+list.get(i).getName()); if(member==null){
	 * Money money = new Money(); money.setName(list.get(i).getName());
	 * money.setPay("否");
	 * money.setOperator(String.valueOf(request.getSession().getAttribute
	 * ("userid"))); money.setInvoicenumber("2019-5-12");
	 * money.setStandard("否"); money.addFamily(); } } process(request, response,
	 * "/page/money/money_list.jsp");
	 * 
	 * } catch (Exception e) { e.printStackTrace();
	 * 
	 * } }
	 */

}
